package cn.bob.basic.jwt;

import cn.bob.user.domain.Logininfo;
import lombok.extern.slf4j.Slf4j;


import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * @author bob
 * @data 2022/10/28-11:56
 */
@Slf4j
public class LoginContext {
    /**
     * 获取前端的登录用户
     * 将用户的名字用来做登录请求
     * 获取登录用户在请求头中返回的数据
     */
    public static Logininfo getLogininfo(HttpServletRequest request){
        try {
            //获取到请求头中的token
            String token = request.getHeader("token");
            if (token==null){
                return null;
            }
            //进行解析 先获取pub公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtRasHolder.INSTANCE.getPubKeyData());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);

            Logininfo logininfo = payload.getUserInfo().getLogininfo();
            if (logininfo==null){
                log.error("payloadData is null!");
                return null;
            }
            return logininfo;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
